{% extends "inventory/base.html" %}
{% load static %}

{% block title %}条码扫描{% endblock %}

{% block extra_css %}
<style>
    #scanner-container {
        width: 100%;
        height: 300px;
        position: relative;
        border: 2px dashed #ccc;
        border-radius: 8px;
        overflow: hidden;
    }
    
    #scanner-container video {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    #scanner-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background-color: rgba(0, 0, 0, 0.5);
        color: white;
        z-index: 10;
    }
    
    .scan-result {
        padding: 15px;
        margin-top: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
    }
    
    .product-info {
        background-color: #e8f4ff;
    }
    
    .batch-info {
        background-color: #f8f4e5;
    }
</style>
{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="card shadow">
        <div class="card-header bg-primary text-white">
            <h5 class="mb-0">条码扫描</h5>
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-6">
                    <div class="card mb-3">
                        <div class="card-header bg-light">
                            <h6 class="mb-0">扫描器</h6>
                        </div>
                        <div class="card-body">
                            <div id="scanner-container">
                                <div id="scanner-overlay">
                                    <i class="fas fa-camera fa-3x mb-2"></i>
                                    <p>点击开始扫描</p>
                                </div>
                            </div>
                            
                            <div class="row mt-3">
                                <div class="col-12">
                                    <div class="d-flex justify-content-between">
                                        <button id="start-scanner" class="btn btn-primary">
                                            <i class="fas fa-qrcode"></i> 开始扫描
                                        </button>
                                        <button id="stop-scanner" class="btn btn-secondary" disabled>
                                            <i class="fas fa-stop"></i> 停止扫描
                                        </button>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="form-group mt-3">
                                <label for="barcode-input">手动输入条码</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="barcode-input" placeholder="输入条码...">
                                    <button class="btn btn-outline-primary" type="button" id="lookup-barcode">
                                        <i class="fas fa-search"></i> 查询
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="card mb-3">
                        <div class="card-header bg-light">
                            <h6 class="mb-0">扫描结果</h6>
                        </div>
                        <div class="card-body">
                            <div id="scan-results-container">
                                <div class="scan-waiting text-center py-5">
                                    <i class="fas fa-barcode fa-3x text-muted mb-3"></i>
                                    <p class="text-muted">等待扫描条码...</p>
                                </div>
                                
                                <!-- 扫描结果将会显示在这里 -->
                                <div id="product-result" class="scan-result product-info d-none">
                                    <h5 class="mb-3">商品信息</h5>
                                    <div class="row">
                                        <div class="col-4 fw-bold">商品名称:</div>
                                        <div class="col-8" id="product-name"></div>
                                        
                                        <div class="col-4 fw-bold">零售价格:</div>
                                        <div class="col-8" id="product-price"></div>
                                        
                                        <div class="col-4 fw-bold">当前库存:</div>
                                        <div class="col-8" id="product-stock"></div>
                                        
                                        <div class="col-4 fw-bold">条码:</div>
                                        <div class="col-8" id="product-barcode"></div>
                                    </div>
                                    
                                    <div class="d-flex justify-content-end mt-3">
                                        <a href="#" id="product-detail-link" class="btn btn-sm btn-info me-2">
                                            <i class="fas fa-eye"></i> 查看详情
                                        </a>
                                        <a href="#" id="product-edit-link" class="btn btn-sm btn-primary">
                                            <i class="fas fa-edit"></i> 编辑
                                        </a>
                                    </div>
                                </div>
                                
                                <div id="batch-result" class="scan-result batch-info d-none">
                                    <h5 class="mb-3">批次信息</h5>
                                    <div class="row">
                                        <div class="col-4 fw-bold">商品名称:</div>
                                        <div class="col-8" id="batch-product-name"></div>
                                        
                                        <div class="col-4 fw-bold">批次编号:</div>
                                        <div class="col-8" id="batch-number"></div>
                                        
                                        <div class="col-4 fw-bold">生产日期:</div>
                                        <div class="col-8" id="batch-mfg-date"></div>
                                        
                                        <div class="col-4 fw-bold">有效期至:</div>
                                        <div class="col-8" id="batch-exp-date"></div>
                                        
                                        <div class="col-4 fw-bold">剩余数量:</div>
                                        <div class="col-8" id="batch-quantity"></div>
                                    </div>
                                    
                                    <div class="d-flex justify-content-end mt-3">
                                        <a href="#" id="batch-detail-link" class="btn btn-sm btn-info">
                                            <i class="fas fa-eye"></i> 查看批次详情
                                        </a>
                                    </div>
                                </div>
                                
                                <div id="error-result" class="scan-result bg-danger text-white d-none">
                                    <h5 class="mb-3">错误</h5>
                                    <p id="error-message"></p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://unpkg.com/@zxing/library@latest"></script>
<script>
    $(document).ready(function() {
        let codeReader = new ZXing.BrowserMultiFormatReader();
        let selectedDeviceId;
        let scannerActive = false;
        
        // 开始扫描
        $('#start-scanner').click(function() {
            startScanner();
        });
        
        // 停止扫描
        $('#stop-scanner').click(function() {
            stopScanner();
        });
        
        // 手动查询
        $('#lookup-barcode').click(function() {
            let barcode = $('#barcode-input').val().trim();
            if (barcode) {
                processBarcode(barcode);
            }
        });
        
        // 按Enter键查询
        $('#barcode-input').keypress(function(e) {
            if (e.which == 13) {
                let barcode = $(this).val().trim();
                if (barcode) {
                    processBarcode(barcode);
                }
                return false;
            }
        });
        
        function startScanner() {
            $('#scanner-overlay').hide();
            codeReader.listVideoInputDevices()
                .then((videoInputDevices) => {
                    selectedDeviceId = videoInputDevices[0].deviceId;
                    
                    // 开始解码
                    codeReader.decodeFromVideoDevice(selectedDeviceId, 'scanner-container', (result, err) => {
                        if (result) {
                            console.log(result);
                            processBarcode(result.text);
                        }
                        if (err && !(err instanceof ZXing.NotFoundException)) {
                            console.error(err);
                        }
                    });
                    
                    scannerActive = true;
                    $('#start-scanner').prop('disabled', true);
                    $('#stop-scanner').prop('disabled', false);
                })
                .catch((err) => {
                    console.error(err);
                    showError('无法访问摄像头。请确保您已授予摄像头访问权限。');
                });
        }
        
        function stopScanner() {
            codeReader.reset();
            scannerActive = false;
            $('#start-scanner').prop('disabled', false);
            $('#stop-scanner').prop('disabled', true);
            $('#scanner-overlay').show();
        }
        
        function processBarcode(barcode) {
            // 清除之前的结果
            hideAllResults();
            
            // AJAX请求获取条码信息
            $.ajax({
                url: '/api/scan-barcode/',
                method: 'POST',
                data: {
                    'barcode_data': barcode,
                    'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
                },
                success: function(response) {
                    console.log(response);
                    
                    if (response.type === 'product') {
                        displayProductInfo(response.data);
                    } else if (response.type === 'batch') {
                        displayBatchInfo(response.data);
                    }
                },
                error: function(xhr) {
                    let errorMsg = '条码扫描失败';
                    if (xhr.responseJSON && xhr.responseJSON.error) {
                        errorMsg = xhr.responseJSON.error;
                    }
                    showError(errorMsg);
                }
            });
        }
        
        function displayProductInfo(product) {
            $('#product-name').text(product.name);
            $('#product-price').text('¥' + product.retail_price.toFixed(2));
            $('#product-stock').text(product.inventory);
            $('#product-barcode').text(product.barcode);
            
            $('#product-detail-link').attr('href', '/products/' + product.id + '/');
            $('#product-edit-link').attr('href', '/products/' + product.id + '/edit/');
            
            $('#product-result').removeClass('d-none');
        }
        
        function displayBatchInfo(batch) {
            $('#batch-product-name').text(batch.product.name);
            $('#batch-number').text(batch.batch_number);
            $('#batch-mfg-date').text(batch.manufacturing_date || '未指定');
            $('#batch-exp-date').text(batch.expiry_date || '未指定');
            $('#batch-quantity').text(batch.remaining_quantity);
            
            $('#batch-detail-link').attr('href', '/products/batches/' + batch.id + '/');
            
            $('#batch-result').removeClass('d-none');
        }
        
        function showError(message) {
            $('#error-message').text(message);
            $('#error-result').removeClass('d-none');
        }
        
        function hideAllResults() {
            $('#product-result').addClass('d-none');
            $('#batch-result').addClass('d-none');
            $('#error-result').addClass('d-none');
        }
    });
</script>
{% endblock %} 